import { isArray } from 'lodash-es'

const dicts = Object.create(null)

dicts.demo = () => [
  { label: '是', value: true },
  { label: '否', value: false }
]

export function addDicts(newDitcs) {
  Object.assign(dicts, newDitcs)
}

for (const key in dicts) {
  dicts[key].formatter = formatter
}

function formatter(value, options) {
  options = options || this()
  isArray(value) || (value = [value])
  return value.map(v => options.find(option => option.value === v)?.label).filter(Boolean)
}

export default {
  props: {
    dicts: {
      type: Object,
      default: () => Object.create(null)
    }
  },
  methods: {
    setOptionsByDict(item) {
      const options = this.dicts[item.dict] || dicts[item.dict]
      if (!options) {
        return
      }

      if (typeof options === 'function') {
        return Promise.resolve(options()).then(options => this.$set(item, 'options', options))
      }

      this.$set(item, 'options', options)
    },

    setFormatterByDict(column) {
      if (!(this.dicts[column.dict] || dicts[column.dict])) return

      this.$set(column, 'formatter', (row, col, value) =>
        (this.dicts[column.dict] || dicts[column.dict]).formatter(value)
      )
    }
  }
}
